package com.maltys.dp.sequence;

/**
 * @author malty
 * @link <a href="https://leetcode.com/problems/longest-palindromic-subsequence/">最长回文子序列</a>
 */
public class LongestPalindromicSubsequence {
    public static void main(String[] args) {
        LongestPalindromicSubsequence subsequence = new LongestPalindromicSubsequence();
        int length = subsequence.longestPalindromeSubsequence("abcba");
        System.out.println(length);
    }

    public int longestPalindromeSubsequence(String s) {
        int[][] dp = new int[s.length() + 1][s.length() + 1];
        for (int i = 0; i <= s.length(); i++) {
            dp[i][i] = 1;
        }
        for (int i = s.length(); i > 0; i--) {
            for (int j = i + 1; j <= s.length(); j++) {
                if (s.charAt(i - 1) == s.charAt(j - 1)) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[1][s.length()];
    }
}
